<template>
  <div class="scroll">
    <div class="content van-mine">
      <div class="left" ref="left">
        <ul>
          <li
            v-for="(item, index) in data"
            :key="index"
            :class="{current: currentIndex == index}"
            @click="selectItem(index, $event)"
          >
            <span class="left-item">{{item.foodTypeName}}</span>
          </li>
        </ul>
      </div>
      <div class="right" ref="right">
        <ul>
          <li class="right-item right-item-hook" v-for="item in data" :key="item.name">
            <h2>{{item.foodTypeName}}</h2>
            <ul>
              <li v-for="(itm,inx) in item.bcFoodVoList" :key="inx">
                <div class="showItem">
                  <div class="left-food">
                    <div class="left-img">
                      <img src="../assets/images/ada.jpg" alt />
                    </div>
                    <div class="leftInfo">
                      <p>{{itm.foodName}}</p>
                      <p>¥ {{itm.foodPrice / 100}}</p>
                    </div>
                  </div>
                  <div class="right-num">
                    <van-stepper
                      disable-input
                      v-model="itm.copies"
                      min="0"
                      @plus="plus(itm.foodId)"
                      @minus="minus(itm.foodId)"
                    />
                  </div>
                </div>
              </li>
            </ul>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>
<script>
import BScroll from "better-scroll";
export default {
  props: {
    dishList: {
      type: Array,
      default() {
        return [];
      }
    },
    childData: {
      type: Object,
      default() {
        return null;
      }
    }
  },
  data() {
    return {
      listHeight: [],
      scrollY: 0, //实时获取当前y轴的高度
      clickEvent: false,
      index: 0,
      fatherData: {
        totalPrice: 0,
        infos: []
      }
    };
  },
  watch: {
    childData: {
      handler: function(val) {
        let that = this;
        for (let i in val.infos) {
          for (let j in that.data) {
            for (let k in that.data[j].bcFoodVoList) {
              if (val.infos[i].foodId == that.data[j].bcFoodVoList[k].foodId) {
                that.data[j].bcFoodVoList[k].copies = val.infos[i].foodNum;
              }
            }
          }
        }
      },
      deep: true
    }
  },
  methods: {
    _initScroll() {
      //better-scroll的实现原理是监听了touchStart,touchend事件，所以阻止了默认的事件（preventDefault）
      //所以在这里做点击的话，需要在初始化的时候传递属性click,派发一个点击事件
      //在pc网页浏览模式下，点击事件是不会阻止的，所以可能会出现2次事件，所以为了避免2次，可以在绑定事件的时候把$event传递过去
      this.lefts = new BScroll(this.$refs.left, {
        click: true
      });
      this.rights = new BScroll(this.$refs.right, {
        probeType: 3 //探针的效果，实时获取滚动高度
      });
      //rights这个对象监听事件，实时获取位置pos.y
      this.rights.on("scroll", pos => {
        this.scrollY = Math.abs(Math.round(pos.y));
      });
    },
    _getHeight() {
      let rightItems = this.$refs.right.getElementsByClassName(
        "right-item-hook"
      );
      let height = 0;
      this.listHeight.push(height);
      for (let i = 0; i < rightItems.length; i++) {
        let item = rightItems[i];
        height += item.clientHeight;
        this.listHeight.push(height);
      }
    },
    selectItem(index, event) {
      this.index = index;
      this.clickEvent = true;
      //在better-scroll的派发事件的event和普通浏览器的点击事件event有个属性区别_constructed
      //浏览器原生点击事件没有_constructed所以当时浏览器监听到该属性的时候return掉
      if (!event._constructed) {
        return;
      } else {
        let rightItems = this.$refs.right.getElementsByClassName(
          "right-item-hook"
        );
        let el = rightItems[index];
        this.rights.scrollToElement(el, 300);
      }
    },
    // 加号
    plus(foodId) {
      let that = this;
      let data = that.data;
      for (let i in data) {
        for (let j in data[i].bcFoodVoList) {
          if (foodId == data[i].bcFoodVoList[j].foodId) {
            // 前端计算总价
            that.fatherData.totalPrice =
              that.fatherData.totalPrice +
              Number(data[i].bcFoodVoList[j].foodPrice) / 100;
            // 菜肴分类ID,目前只有标准，只取标准
            let specId = "";
            for (let k in data[i].bcFoodVoList[j].specList) {
              if (data[i].bcFoodVoList[j].specList[k].specName == "标准") {
                specId = data[i].bcFoodVoList[j].specList[k].specId;
              }
            }
            // 判断that.fatherData.infos是不是空，空直接push
            if (that.fatherData.infos.length > 0) {
              // 判断有没有添加过这个菜，有就改写数量，没有就push一条
              for (let k in that.fatherData.infos) {
                if (that.fatherData.infos[k].foodId == foodId) {
                  that.fatherData.infos[k].foodNum =
                    data[i].bcFoodVoList[j].copies + 1;
                  return;
                }
              }
              let info = {
                foodId: data[i].bcFoodVoList[j].foodId, //菜肴id
                specId: specId, //规格id
                foodClassName: data[i].bcFoodVoList[j].foodTypeName, //菜肴分类名称
                foodClassId: data[i].bcFoodVoList[j].foodTypeId, //菜肴分类id
                foodName: data[i].bcFoodVoList[j].foodName, //菜肴名称
                foodNum: data[i].bcFoodVoList[j].copies + 1, //菜肴数量
                foodPrice: data[i].bcFoodVoList[j].foodPrice //菜肴单价
              };
              that.fatherData.infos.push(info);
            } else {
              let info = {
                foodId: data[i].bcFoodVoList[j].foodId, //菜肴id
                specId: specId, //规格id
                foodClassName: data[i].bcFoodVoList[j].foodTypeName, //菜肴分类名称
                foodClassId: data[i].bcFoodVoList[j].foodTypeId, //菜肴分类id
                foodName: data[i].bcFoodVoList[j].foodName, //菜肴名称
                foodNum: data[i].bcFoodVoList[j].copies + 1, //菜肴数量
                foodPrice: data[i].bcFoodVoList[j].foodPrice //菜肴单价
              };
              that.fatherData.infos.push(info);
            }
            that.$emit("success-data", that.fatherData);
          }
        }
      }
    },
    // 减号
    minus(foodId) {
      let that = this;
      let data = that.data;
      for (let i in data) {
        for (let j in data[i].bcFoodVoList) {
          if (foodId == data[i].bcFoodVoList[j].foodId) {
            if (that.fatherData.totalPrice <= 0) {
              that.$toast("都0了，还往哪儿减");
              return;
            } else {
              that.fatherData.totalPrice =
                that.fatherData.totalPrice -
                Number(data[i].bcFoodVoList[j].foodPrice) / 100;
            }
            // 操作已选菜肴
            for (let k in that.fatherData.infos) {
              if (that.fatherData.infos[k].foodId == foodId) {
                that.fatherData.infos[k].foodNum -= 1;
                if (that.fatherData.infos[k].foodNum <= 0) {
                  //如果数量等于0删除此菜肴
                  that.fatherData.infos.splice(k, 1);
                }
              }
            }
            that.$emit("success-data", that.fatherData);
          }
        }
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this._initScroll();
      this._getHeight();
    });
  },
  computed: {
    currentIndex() {
      // 菜少的时候
      if (this.listHeight.length == 1) {
        return this.index;
      }
      for (let i = 0; i < this.listHeight.length; i++) {
        let height = this.listHeight[i];
        let height2 = this.listHeight[i + 1];
        //当height2不存在的时候，或者落在height和height2之间的时候，直接返回当前索引
        //>=height，是因为一开始this.scrollY=0,height=0
        if (!height2 || (this.scrollY >= height && this.scrollY < height2)) {
          if (this.scrollY == 0) {
            return 0;
          }
          if (this.clickEvent) {
            if (this.index == 0) {
              return i;
            } else if (this.index == this.listHeight.length - 2) {
              return this.listHeight.length - 2;
            } else {
              return i + 1;
            }
          } else {
            return i;
          }
        }
      }
      //如果this.listHeight没有的话，就返回0
      return 0;
    },
    // 处理父组件传过来的数据
    data() {
      let that = this;
      that.fatherData.totalPrice = 0;
      that.fatherData.infos = [];
      return that.dishList;
    }
  }
};
</script>
<style scoped>
.van-mine {
  top: 140px !important;
}
.content {
  display: flex;
  position: absolute;
  top: 650px;
  bottom: 250px;
  width: 100%;
  overflow: hidden;
  background: #eee;
}
.left {
  flex: 0 0 450px;
  width: 450px;
  background-color: #f0f0f0;
}
.left li {
  width: 100%;
  height: 100%;
}
.current {
  background-color: #fff;
}
.left-item {
  display: block;
  width: 100%;
  height: 200px;
  line-height: 200px;
  text-align: center;
}
.right {
  flex: 1;
  background-color: #fff;
}
.right-item h2 {
  width: 100%;
  background-color: #f0f0f0;
}
.right-item li {
  width: 100%;
  text-align: center;
  border-bottom: 1px solid #0a7fe5;
}
* {
  list-style: none;
  margin: 0;
  padding: 0;
}
/* start */
.showItem {
  width: 100%;
  padding: 30px 30px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.showItem .left-food {
  display: flex;
  align-items: center;
  background-color: #fff;
}
.showItem .left-food .left-img {
  width: 200px;
  height: 200px;
  margin-right: 20px;
}
.showItem .left-food .left-img img {
  width: 100%;
  height: 100%;
}
.showItem .left-food .leftInfo {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
</style>